package com.joker.demo.controller;


import com.joker.demo.service.StreamAssistant;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import dev.langchain4j.service.spring.AiService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * 流式调用
 *
 * @author : feixiang.li
 * @since : 2025-09-25 16:29
 */
@RestController
@RequestMapping("/streamApi")
public class StreamApiController {

    @Resource
    private StreamingChatModel streamingChatModel;

    @Resource
    private StreamAssistant streamAssistant;

    @RequestMapping("/stream")
    public Flux<String> hello(@RequestParam(value = "question", defaultValue = "你是谁") String question) {

        return Flux.create(emitter -> {
            streamingChatModel.chat(question, new StreamingChatResponseHandler() {
                @Override
                public void onPartialResponse(String s) {
                    emitter.next(s);
                }

                @Override
                public void onCompleteResponse(ChatResponse chatResponse) {
                    emitter.complete();
                }

                @Override
                public void onError(Throwable throwable) {
                    emitter.error(throwable);
                }
            });
        });
    }


    @RequestMapping("/apiHigh")
    public Flux<String> api(@RequestParam(value = "question", defaultValue = "你是谁") String question) {
        return streamAssistant.askStream(question);
    }
}
